﻿#include<stdio.h>

void Swap(int* a,int* b)
{
	int temp = *a;
	*a = *b;
	*b = temp;
}

void Adjust_down(int* arr, int end, int parent)
{
	int child = parent * 2 + 1;
	while (child < end)
	{
		if (child + 1 < end && arr[child] < arr[child + 1])
		{
			child++;
		}
		if (arr[child] > arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapSort(int* arr, int n)
{
	//建堆
	for (int i = (n - 1 - 1) / 2; i >= 0; i--)
	{
		Adjust_down(arr, n, i);
	}

	//排序
	int end = n - 1;
	while (end > 0)
	{
		Swap(&arr[0], &arr[end]);
		Adjust_down(arr, end ,0);
		end--;
	}
}

int main()
{
	int arr1[5] = { 1,2,3,4,5 };
	int arr2[5] = { 5,4,3,2,1 };
	int arr3[5] = { 1,1,2,1,1 };
	//堆排序
	HeapSort(arr1,5);
	HeapSort(arr2,5);
	HeapSort(arr3,5);
	for (int i = 0; i < 5; i++)
	{
		printf("%d ", arr1[i]);
	}
	printf("\n");
	for (int i = 0; i < 5; i++)
	{
		printf("%d ", arr2[i]);
	}
	printf("\n");
	for (int i = 0; i < 5; i++)
	{
		printf("%d ", arr3[i]);
	}
	printf("\n");
	return 0;
}